<!--processed-->
<link rel="stylesheet" href="/src/component/date/datepicker.css">
<link rel="stylesheet" href="/views/coupon/tmp.css">
<section id="coupon">
    <div class="breadcrumb">
        <i class="back iconfont icon-fanhui1" id="back"></i>
        <span>Resolution</span>
        <span class="interval">/</span>
        <span>Coupon</span>
    </div>
    <div class="layout-processed feat-grid">
        <form id="form" action="" class="header fx-col-a">
            <div class="clearfix fx-row-s">

                <div class="header-item fl ml20"><label>department：</label></div>
                <div class="header-item w12 fl">
                    <section data-name="departmentName" class="com-select">
                        <div class="sel-item">
                            <input class="sel-head" type="text" value="" readonly UNSELECTABLE="on" placeholder="Select a department"/>
                            <input name="businessUnitId" type="hidden" value="">
                            <i class="sel-icon"></i>
                        </div>
                        <ul id="departmentName" class="sel-content">
                            <!--事业部填充-->
                        </ul>
                    </section>
                </div>

                <div class="header-item fl ml20"><label>site：</label></div>
                <div class="header-item w12 fl">
                    <section data-name="siteName" class="com-select">
                        <div class="sel-item">
                            <input class="sel-head" type="text" value="" readonly UNSELECTABLE="on" placeholder="Select site"/>
                            <input name="siteId" type="hidden" value="">
                            <i class="sel-icon"></i>
                        </div>
                        <ul id="siteName" class="sel-content">
                            <!--事业部站点填充-->
                        </ul>
                    </section>
                </div>

                <div class="header-item fl ml20"><label>date of Coupon creation：</label></div>
                <div class="header-item fl createTimeReset">
                    <div id="creatCoupon" class="c-datepicker-date-editor J-datepicker-range-day">
                        <i class="c-datepicker-range__icon kxiconfont icon-clock"></i>
                        <input placeholder="Start Date" name="startTime" class="c-datepicker-data-input only-date" value="">
                        <span class="c-datepicker-range-separator">-</span>
                        <input placeholder="End Date" name="endTime" class="c-datepicker-data-input only-date" value="">
                    </div>
                </div>

                <div class="header-item fl ml20"><label>user's email address：</label></div>
                <div class="header-item w12 fl">
                    <input type="text" class="form-input" name="orderUserMail">
                </div>
            </div>

            <div class="clearfix fx-row-s">

                <div class="header-item fl ml20"><label>coupon code：</label></div>
                <div class="header-item w10 fl">
                    <input type="text" class="form-input" name="code">
                </div>

                <div class="header-item fl ml20"><label>status：</label></div>
                <div class="header-item w12 fl">
                    <section data-name="endAtStatus" class="com-select">
                        <div class="sel-item">
                            <input class="sel-head" type="text" value="" readonly UNSELECTABLE="on" placeholder=""/>
                            <input name="endAtStatus" type="hidden" value="">
                            <i class="sel-icon"></i>
                        </div>
                        <ul id="endAtStatus" class="sel-content">
                            <!--事业部站点填充-->
                        </ul>
                    </section>
                </div>

                <div class="header-item fl ml20"><label>disabled or not：</label></div>
                <div class="header-item w10 fl">
                    <section data-name="isDel" class="com-select">
                        <div class="sel-item">
                            <input class="sel-head" type="text" value="" readonly UNSELECTABLE="on" placeholder=""/>
                            <input name="isDel" type="hidden" value="">
                            <i class="sel-icon"></i>
                        </div>
                        <ul id="isDel" class="sel-content">
                            <!--事业部站点填充-->
                        </ul>
                    </section>
                </div>

                <div class="header-item fl ml20"><label>reason：</label></div>
                <div class="header-item w12 fl">
                    <section data-name="reasonId" class="com-select">
                        <div class="sel-item">
                            <input class="sel-head" type="text" value="" readonly UNSELECTABLE="on" placeholder=""/>
                            <input name="reasonId" type="hidden" value="">
                            <i class="sel-icon"></i>
                        </div>
                        <ul id="couponReason" class="sel-content">
                            <!--原因填充-->
                        </ul>
                    </section>
                </div>

                <div class="header-item ml20">
                    <button id="check" class="btn-e ml10" type="button">search</button>
                    <button id="export" type="button" class="btn-b">Derive</button>
                </div>
            </div>
        </form>
        <div class="data-box com-check">
            <table class="table-a table-fixed" style="overflow: hidden;">
                <thead class="t-head">
                <tr>
                    <th class="tc">number</th>
                    <th>department</th>
                    <th>site</th>
                    <th>customer service</th>
                    <th>Date of creation</th>
                    <th>Order Number</th>
                    <th>coupon code</th>
                    <th>amount</th>
                    <th>currency</th>
                    <th>reason</th>
                    <th>status</th>
                    <th class="w12">operation</th>
                </tr>
                </thead>
                <tbody data-name="coupon-data">

                </tbody>
            </table>
        </div>

    </div>

    <footer class="footer fx-row-b">
        <div>
            <span>Showing <span id="page-start">1</span> to <span id="page-end">20</span> of <span id="page-total">0</span> entries</span>
            <select name="page">
                <option value="10">10</option>
                <option value="20">20</option>
                <option value="30">30</option>
                <option value="50">50</option>
                <option value="100">100</option>
            </select>
            <span>records per page</span>
        </div>
        <section id="box-page"></section>
    </footer>
</section>

<!--渲染模板开始-->

<!--事业部列表-->
<script id="coupon-list" type="text/html">
    {{each businessUnitId as v i}}
    {{if (i>0)}}
        <li data-val="{{i}}" class="sel-list">{{v}}</li>
    {{/if}}
    {{/each}}
</script>


<!--事业部-站点列表-->
<script id="coupon-point" type="text/html">
    {{each data as v i}}
    <li data-val="{{i}}" class="sel-list">{{v}}</li>
    {{/each}}
</script>

<!--有效期-->
<script id="coupon-endAtStatus" type="text/html">
    {{each endAtStatus as v i}}
    <li data-val="{{i}}" class="sel-list">{{v}}</li>
    {{/each}}
</script>

<!--是否禁用-->
<script id="coupon-isDel" type="text/html">
    {{each isDel as v i}}
    <li data-val="{{i}}" class="sel-list">{{v}}</li>
    {{/each}}
</script>

<!--优惠券一级原因-->
<script id="coupon-list-reason" type="text/html">
    <li data-val="" class="sel-list">All</li>
    {{each reasonId as v i}}
    <li data-val="{{v.Id}}" class="sel-list">{{v.Name}}</li>
    {{/each}}
</script>

<!--list data-->
<script id="coupon-list-data" type="text/html">

    {{each list as v i}}
    <tr class="nth">
        <td class="tc"><span>{{i + $imports.count}}</span></td>
        <td>{{v.business_unit_name}}</td>
        <td>{{v.site_name}}</td>
        <td>{{v.create_by_name}}</td>
        <td>{{v.create_at}}</td>
        <td>{{v.order_no}}</td>
        <td>{{v.code}}</td>
        <td>{{v.amount}}</td>
        <td>{{v.currency_code}}</td>
        <td>{{v.reason_parent_title}} <br/> {{v.reason_title}} <br/> {{v.reason}}</td>
        <td>{{v.status_msg}}</td>
        <td class="w12">
            <div class="row" data-record="{{JSON.stringify(v)}}">
                <div class="col-sm-8"><a class="coupon-detail" href="javascript:;">Details</a></div>
                <div class="col-sm-8"><button class="coupon-edit btn-a1" {{v.is_edit ? 'disabled' : ''}} >Edit</button></div>
                <div class="col-sm-8"><button class="coupon-del btn-a2" {{v.is_del ? 'disabled' : ''}}>Disable</button></div>
            </div>
        </td>
    </tr>
    {{/each}}

</script>



<!--生成优惠券弹出的模板dom-->
<script id="coupon-list-detail" type="text/html">
    <section class="box-content">
        <div class="row">
            <div class="col-sm-8">
                <label>user's email address：</label>
                <span data-name="order_user_mail"></span>
            </div>
            <div class="col-sm-13">
                <label>Active Dates：</label>
                <span data-name="start_at"></span>&nbsp;&nbsp;
                <span data-name="end_at"></span>
            </div>
            <div class="col-sm-3">
                <label>quatity：</label>
                <span data-name="num"></span>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-8">
                <label>SKU of items：</label>
                <span data-name="sku_list"></span>
            </div>
            <div class="col-sm-8">
                <label>Update time：</label>
                <span data-name="update_at"></span>
            </div>
        </div>
    </section>
</script>


<!--生成优惠券弹出的模板dom-->
<script id="coupon-list-edit" type="text/html">
    <section>
        <div class="box-content">
            <div style="padding:20px 0;">
                <div id="editCoupon" class="c-datepicker-date-editor  J-datepicker-range-day">
                    <i class="c-datepicker-range__icon kxiconfont icon-clock"></i>
                    <input placeholder="start Date" name="editStartTime" class="c-datepicker-data-input only-date" value="">
                    <span class="c-datepicker-range-separator">-</span>
                    <input placeholder="end Date" name="editEndTime" class="c-datepicker-data-input only-date" value="">
                </div>
            </div>
        </div>
    </section>
</script>


<!-- js -->
<script>

    $.extend(window.p,{
        page:1,
        num:20,
        total:0,
        pageObj:null,
        src : [
            "/src/component/date/moment.min.js",
            "/src/component/date/datepicker.all.js",
        ],
        increment:$("#increment").comCheck(),
        data:{
            export:0
        },
        siteObj:null,
        layerObj:null,
        layerEditObj:null,
    });

    $(function(){

        init();

        function init(){

            if(com.getCookie('pageNum')) {
                p.num = com.getCookie("pageNum");
            }

            //默认分页显示
            $("select[name='page']").val(p.num);
            //返回
            $(".back").click(function(){
                window.history.go(-1);
            });

            //初始化分页
            initPage();

            //选择分页事件
            $("select[name='page']").on('change',function(){
                var val = $(this).val();
                com.setCookie('pageNum',val,720);
                p.num = val;
                request();
            });

            template.defaults.imports.JSON = JSON;

            //初始化日期组件(js暂时插入当前页面模块 / 后期处理性能问题【2】)
            app.dynamicLoadJs(p.src,'coupon',function(){
                $('#creatCoupon').datePicker({
                    hasShortcut: true,
                    format: 'YYYY-MM-DD HH:mm:ss',
                    isRange: true,
                    shortcutOptions: [
                        {
                            name: 'Last week',
                            day: '-7,0'
                        },
                        {
                            name: 'Last M',
                            day: '-30,0'
                        },
                        {
                            name: 'Last six M',
                            day: '-180,0'
                        },
                        {
                            name: 'Last Y',
                            day: '-365,0'
                        }
                    ]
                });
                setTime();
            });

            //初始化对应站点
            p.siteObj = $("[data-name='siteName']").comSelect({
                init:true,
                search:true,
            });

            //默认请求事业部
            requestDivision();

            //查询按钮
            $("#check").on('click',function(){
                p.data.export = 0;
                request('init');
            })

            $("#export").on('click',function(){
                p.data.export = 1;
                exportList();
            })

            var couponDataBody =  $("[data-name='coupon-data']");
            //详情按钮
            couponDataBody.on('click','.coupon-detail',function(){
                var _this = $(this);
                var dom = $("#coupon-list-detail").html();
                p.layerObj = new ComLayer({
                    dom:dom,
                    title:'Details',
                    width:'800px',
                    okHandler:function(){
                        p.layerObj.close();
                    },
                    callback:function(){
                        var res = _this.closest('.row').data();
                        var data = res.record;
                        $("[data-name='order_user_mail']").html(data.order_user_mail);
                        $("[data-name='end_at']").html(data.end_at);
                        $("[data-name='start_at']").html(data.start_at);
                        $("[data-name='num']").html(data.num);
                        $("[data-name='sku_list']").html(productInfo(data.sku_list));
                        $("[data-name='update_at']").html(data.update_at);
                    }
                })
            })

            //编辑按钮
            couponDataBody.on('click','.coupon-edit',function(){
                var _this = $(this);
                var dom = $("#coupon-list-edit").html();
                p.layerEditObj = new ComLayer({
                    dom:dom,
                    title:'Edit coupon',
                    zIndex:800,
                    okHandler:function(btnObj){
                        var res = _this.closest('.row').data();
                        //调用编辑优惠券接口
                        editCoupon(res.record,btnObj)
                    },
                    callback:function(){
                        $('#editCoupon').datePicker({
                            hasShortcut: true,
                            format: 'YYYY-MM-DD HH:mm:ss',
                            isRange: true,
                            shortcutOptions: []
                        });
                    }
                })
            })

            //禁用按钮
            couponDataBody.on('click','.coupon-del',function(){
                var _this = $(this);
                var res = _this.closest('.row').data();
                $.alert({
                    message:'Please reconfirm if you want to disable this coupon. If confirmed, can this coupon not be edited or enabled again?',
                    //detail:'oon shit pop push',
                    okHandler:function(){
                        couponDel(res.record);
                    },
                    okText:'Confirm',
                    cancelText:'cancel'
                })
            })


        }


        function initPage(){
            p.pageObj = $("#box-page").comPage({
                total:p.total,
                pages:p.num,
                callback:function(page){
                    p.page = page;
                    request();
                }
            });
        }

        function renderLeftPage(){
            $("#page-total").html(p.total);
            $("#page-start").html((p.page-1)*p.num + 1);
            if(p.page === 1){
                $("#page-end").html(p.num);
            }else if(p.page == Math.ceil(p.total/p.num)) {
                $("#page-end").html(p.total);
            }else{
                $("#page-end").html(p.page*p.num);
            }
        }

        //默认请求事业部
        function requestDivision(){
            app.ajax({
                type:'get',
                url:app.api('/api/coupon/getSearchSelect'),
                data:{},
                success:function(res){
                    if(res.code == 0){
                        var listTmp = template('coupon-list', res.data);
                        $("#departmentName").html(listTmp);

                        $("[data-name='departmentName']").comSelect({
                            init:true,
                            callback:function(val,text){
                                requestSite(val);
                            }
                        });
                        requestSite(1);

                        renderOuther(res);
                    }else{
                        $.comMessage({
                            type:'warning',
                            text:res.msg,
                        });
                    }
                }
            });
        }


        //默认请求事业部对应的站点名
        function requestSite(val){

            var d = JSON.stringify({
                businessUnitId:val
            })
            app.ajax({
                type:'post',
                url:app.api('/api/coupon/getSiteInfoByBid'),
                data:d,
                success:function(res){
                    if(res.code == 0){
                        var listTmp = template('coupon-point', res);
                        $("#siteName").html(listTmp);

                        p.siteObj.init();
                    }else{
                        $.comMessage({
                            type:'warning',
                            text:res.msg,
                        });
                    }
                }
            });
        }

        //默认请求原因
        function renderOuther(res){
            var endAtStatusTmp = template('coupon-endAtStatus', res.data);
            $("#endAtStatus").html(endAtStatusTmp);
            var isDelTmp = template('coupon-isDel', res.data);
            $("#isDel").html(isDelTmp);
            var reasonTmp = template('coupon-list-reason',res.data);
            $("#couponReason").html(reasonTmp);


            $("[data-name='endAtStatus']").comSelect({
                init:true,
                search:true,
            });
            $("[data-name='isDel']").comSelect({
                init:true,
                search:true,
            });
            $("[data-name='reasonId']").comSelect({
                init:true,
            });
        }

        //更改原因字段
        function filterReason(reasonArr){
            var arr = [];
            $.each(reasonArr,function(index,item){
                var obj = {
                    label:item.Name,
                    value:item.Id,
                    children:[]
                }
                if(item.ChildProblemData && item.ChildProblemData.length>=1){
                    obj.children = filterReason(item.ChildProblemData)
                }
                arr.push(obj);
            });
            return arr;
        }

        //请求列表
        function request(init){

            init && (p.page = 1);

            var loadObj = null;
            app.ajax({
                type:'post',
                url:app.api('/api/coupon/list'),
                data:JSON.stringify(getPara()),
                beforeSend:function(){
                    loadObj = $.load({insert:$(".layout-processed"),});
                    $('footer').removeClass('hide')
                },
                success:function(res){
                    template.defaults.imports.count = (p.page-1)*p.num + 1;
                    if(res.code == 0){

                        var tmp = template('coupon-list-data', res.data);
                        $("[data-name='coupon-data']").html(tmp);

                        p.total = res.data.total;

                        if(init){
                            p.pageObj.setPage(p.total,p.num,1);
                        }else{
                            p.pageObj.setPage(p.total,p.num);
                        }
                        renderLeftPage();

                    }else{
                        $.comMessage({
                            type:'warning',
                            text:res.msg,
                        });
                        $("[data-name='siteData']").html('');
                        $("[data-name='siteDataTotal']").html('');
                        $('footer').addClass('hide')
                    }
                },
                complete:function(){
                    loadObj.close()
                }
            });
        }


        //导出列表
        function exportList(){
            var base = '/api/coupon/export?data=' + JSON.stringify(getPara());
            var url = app.api(base);
            window.open(url,'_blank')
        }

        //编辑优惠券
        function editCoupon(record,btnObj){
            var startTime = $("[name='editStartTime']").val();
            var endTime = $("[name='editEndTime']").val();
            //return;
            var data = {
                siteId:record.site_id,
                id:record.id,
                startTime:startTime,
                endTime:endTime
            };
            app.ajax({
                type:'post',
                url:app.api('/api/coupon/update'),
                data:JSON.stringify(data),
                beforeSend:function(){
                    btnObj.addClass('active-animate').prop('disabled',true)
                },
                success:function(res){
                    if(res.code == 0){
                        p.layerEditObj.close();
                        $.comMessage({
                            type:'prompt',
                            text:res.message,
                        });
                        request();
                    }else{
                        $.comMessage({
                            type:'warning',
                            text:res.message,
                        });
                    }
                },
                complete:function(){
                    btnObj.removeClass('active-animate').prop('disabled',false)
                }
            });
        }
        //禁用优惠券
        function couponDel(record){
            var data = {
                siteId:record.site_id,
                id:record.id,
            };
            app.ajax({
                type:'post',
                url:app.api('/api/coupon/delete'),
                data:JSON.stringify(data),
                beforeSend:function(){
                },
                success:function(res){
                    if(res.code == 0){
                        $.comMessage({
                            type:'prompt',
                            text:res.message,
                        });
                        request();
                    }else{
                        $.comMessage({
                            type:'warning',
                            text:res.message,
                        });
                    }
                },
                complete:function(){
                }
            });
        }

        //获取列表参数
        function getPara(){
            $.each($("#form").serializeArray(),function(index,item){
                p.data[item.name] = item.value ;
            });

            p.data.page = p.page;
            p.data.limit = p.num;
            return p.data;
        }

        function setTime(){
            var t = new Date().getTime();
            var oldTime = t - 86400*7*1000;
            var start = com.formatDate(oldTime,'-').split(' ')[0];
            var end = com.formatDate(t,'-').split(' ')[0];
            $("input[name='startTime']").val(end + " 00:00:00");
            $("input[name='endTime']").val(end + " 23:59:59");
        }

        function productInfo(str){
            var arr = str.split(',');
            var tmp = "";
            $.each(arr,function(index,item){
                tmp+=("<div>"+item+"</div>")
            })
            return tmp;
        }

    })


</script>